package org.lib.webvalidation.controller;

import java.util.List;

import javax.validation.Valid;

import org.lib.webvalidation.dto.Hello4DTO;
import org.lib.webvalidation.dto.NameDTO;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Web接口
 * @author ben
 * @date 2021-09-26 09:48:27 CST
 */
@RestController
@RequestMapping(value="/web")
public class WebController {

	/**
	 * hello
	 * 校验1：代码中硬编码
	 * @author ben
	 * @date 2021-09-26 09:56:53 CST
	 * @param name
	 * @return
	 */
	@GetMapping(value="/hello")
	public String hello(@RequestParam String name) {
		// 校验
		if (!StringUtils.hasText(name)) {
			// name为空
			throw new RuntimeException("name不能为空");
		}
		final int nameMaxLen = 100;
		if (name.length() > nameMaxLen) {
			// 最大长度校验
			// 抛出异常
			throw new RuntimeException("name长度超过" + nameMaxLen);
		}
		
		return "Hello, " + name;
	}
	
	/**
	 * hello2
	 * 校验2：校验DTO + @Valid 注解
	 * @author ben
	 * @date 2021-09-26 10:26:43 CST
	 * @param dto
	 * @return
	 */
	@GetMapping(value="/hello2")
	public String hello2(@Valid NameDTO dto) {
		return "Hello, " + dto.getName();
	}

	/**
	 * hello3
	 * 校验2：校验DTO + @Valid 注解
	 * @author ben
	 * @date 2021-09-26 10:58:53 CST
	 * @param dto
	 * @return
	 */
	@GetMapping(value="/hello3")
	public String hello3(@Validated NameDTO dto) {
		return "Hello, " + dto.getName();
	}

	/**
	 * POST请求参数校验
	 * @author ben
	 * @date 2021-09-26 13:08:53 CST
	 * @param dto
	 * @return
	 */
	@PostMapping(value="/hello4")
	public String hello4(@RequestBody @Validated Hello4DTO dto) {
		return "Hello, " + dto.getName() + ", you are " + dto.getAge();
	}
	
	/**
	 * 使用BindingResult返回错误信息
	 * @author ben
	 * @date 2021-09-26 14:17:03 CST
	 * @param dto
	 * @param bresult
	 * @return
	 */
	@PostMapping(value="/hello5")
	public String hello5(@RequestBody @Validated Hello4DTO dto, BindingResult bresult) {
		if (bresult.hasErrors()) {
			// 参数校验错误处理：返回所有错误信息
			StringBuffer sb = new StringBuffer();
			List<ObjectError> oel = bresult.getAllErrors();
			sb.append("API中-参数错误：");
			oel.forEach(oe->{
				sb.append(oe.getDefaultMessage() + ";");
			});
			return sb.toString();
		}
		
		return "Hello, " + dto.getName() + ", you are " + dto.getAge();
	}
	
}
